package com.cotton.utils;

import java.util.Comparator;
import java.util.Map;

import org.apache.log4j.Logger;

/**
 * 版权：上海投投金融信息服务有限公司 
 * 功能：公用排序
 * 作者：朱伟峰 
 * 邮箱：zhuweifeng24@gmail.com
 * 日期：2016年02月02日
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public class ListMapSort implements Comparator
{
	private static Logger logger = Logger.getLogger(ListMapSort.class);
	
	private String sort;

	public ListMapSort(String sort)
	{
		this.sort = sort;
	}
	
	@Override
	public int compare(Object o1, Object o2)
	{
		Map<String, Object> c1 = (Map<String, Object>) o1;
		Map<String, Object> c2 = (Map<String, Object>) o2;
		
		Object obj1 = c1.get(sort);
		Object obj2 = c2.get(sort);
		if (obj1 == null || obj2 == null)
			return 0;
		
		String v1 = obj1.toString();
		String v2 = obj2.toString();
		if (Tools.isTrimEmpty(v1) || Tools.isTrimEmpty(v2))
			return 0;
		
		try
		{
			if (obj1 instanceof String) 
				return v1.compareToIgnoreCase(v2);
			else if (obj1 instanceof Integer) 
				return returnIntegerValue(Tools.genInt(v1), Tools.genInt(v2));
			else if (obj1 instanceof Long)
				return returnLongValue(Tools.genLong(v1), Tools.genLong(v2));
			else if (obj1 instanceof Double)
				return returnDoubleValue(Tools.genDouble(v1), Tools.genDouble(v2));
			else
				return 0;
		}
		catch (Exception e)
		{
			logger.error("", e);
			return 0;
		}
	}
	
	private int returnIntegerValue(int o1, int o2)
	{
		try
		{
			if (o1 > o2) return 1;
			else if (o1 < o2) return -1;
			else return 0;
		}
		catch (Exception e) 
		{
			logger.error("", e);
			return 0;
		}
	}
	
	private int returnDoubleValue(double o1, double o2)
	{
		try
		{
			if (o1 > o2) return 1;
			else if (o1 < o2) return -1;
			else return 0;
		}
		catch (Exception e) 
		{
			logger.error("", e);
			return 0;
		}
	}
	
	private int returnLongValue(long o1, long o2)
	{
		try
		{
			if (o1 > o2) return 1;
			else if (o1 < o2) return -1;
			else return 0;
		}
		catch (Exception e) 
		{
			logger.error("", e);
			return 0;
		}
	}
	
}
